package com.rzhd.coursepatriarch.common.utils.permission;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.rzhd.coursepatriarch.common.R;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.Setting;

import java.util.List;

/**
 * 权限请求处理类
 * <p>
 * 1.请求单个权限或者权限组的时候使用的是Permission这个类下的
 * 如：Permission.WRITE_EXTERNAL_STORAGE
 * <p>
 * 2.AndPermission可以在任何地方使用
 * 如：AndPermission.with(activity/fragment/context)
 * <p>
 * 3.当用户拒绝时想要再次申请调用Rationale方法，在该方法中去申请
 * <p>
 * 4.AndPermission.hasAlwaysDeniedPermission只能在onDenied()的回调中调用，不能在其它地方使用
 *
 * @author yql
 * @date: 2018/10/11.
 */
public class AndPermissionUtils {

    private Context mContext;
    private AddPermissionCallback mAddPermissionCallback;
    String CHECK_OP_NO_THROW = "checkOpNoThrow";
    String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";

    /**
     * 版本更新需要的权限
     */
    public static final String[] versionUpdatePermissions = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};

    /**
     * 上传拿图片需要的权限
     */
    public static final String[] picturePermissions = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA};

    /**
     * 扫描二维码需要的权限
     */
    public static final String[] twoCodePermissions = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA};


    /**
     * 录制视频\直播 需要的权限
     */
    public static final String[] recordPermissions = {
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA};


    /**
     * 存储权限
     */
    public static final String[] storagePermissions = {
            Manifest.permission.READ_EXTERNAL_STORAGE };

    /**
     * 启动页需要获取的权限
     */
    public static final String[] splashPermissions = {
            Manifest.permission.READ_EXTERNAL_STORAGE ,
            Manifest.permission.ACCESS_COARSE_LOCATION ,
            Manifest.permission.ACCESS_FINE_LOCATION };

    public AndPermissionUtils(Context context, AddPermissionCallback mAddPermissionCallback) {
        mContext = context;
        this.mAddPermissionCallback = mAddPermissionCallback;
    }

    /**
     * Request permissions.
     */
    public void requestPermission(String... permissions) {

//        if (AndPermission.hasPermissions(mContext, permissions)) {
//            if (mAddPermissionCallback != null) {
//                mAddPermissionCallback.onGranted(Arrays.asList(permissions));
//            }
//            return;
//        }

        AndPermission.with(mContext)
                .runtime()
                .permission(permissions)
                .rationale(new RuntimeRationale())
                .onGranted(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> permissions) {
                        if (!PermissionElsePhoneUtils.hasPermissions(mContext, permissions)) {
                            if (mAddPermissionCallback != null) {
                                mAddPermissionCallback.onDenied(permissions);
                            }
                            return;
                        }
                        if (mAddPermissionCallback != null) {
                            mAddPermissionCallback.onGranted(permissions);
                        }
                    }
                })
                //当在弹出的权限弹窗勾选禁止后会执行onAction方法
                .onDenied(new Action<List<String>>() {
                    @Override
                    public void onAction(@NonNull List<String> permissions) {
                        if (AndPermission.hasAlwaysDeniedPermission(mContext, permissions)) {
                            showSettingDialog(mContext, permissions);
                            return;
                        }
                        if (mAddPermissionCallback != null) {
                            mAddPermissionCallback.onDenied(permissions);
                        }
                    }
                })
                .start();
    }

    /**
     * Display setting dialog.
     */
    private void showSettingDialog(Context context, final List<String> permissions) {
        List<String> permissionNames = Permission.transformText(context, permissions);
        String message = context.getString(R.string.message_permission_always_failed, TextUtils.join("\n", permissionNames));

        new AlertDialog.Builder(context)
                .setCancelable(false)
                .setTitle(R.string.title_dialog)
                .setMessage(message)
                .setPositiveButton(R.string.setting, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        setPermission();
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (mAddPermissionCallback != null) {
                            mAddPermissionCallback.onDenied(permissions);
                        }
                    }
                })
                .show();
    }

    /**
     * Set permissions.
     */
    private void setPermission() {
        AndPermission.with(mContext)
                .runtime()
                .setting()
                .onComeback(new Setting.Action() {
                    @Override
                    public void onAction() {
                        //设置权限后返回
                        if (mAddPermissionCallback != null) {
                            mAddPermissionCallback.onComeback();
                        }
                    }
                })
                .start();
    }

    /**
     * 检查是否有权限
     *
     * @param permissions
     * @return
     */
    public boolean hasPermissions(String... permissions) {
        if (AndPermission.hasPermissions(mContext, permissions)) {
            return true;
        }
        return false;
    }

    public interface AddPermissionCallback {
        /**
         * 权限请求成功
         *
         * @param permissions
         */
        void onGranted(@NonNull List<String> permissions);

        /**
         * 权限请求失败
         *
         * @param permissions
         */
        void onDenied(@NonNull List<String> permissions);

        /**
         * 权限设置返回
         */
        void onComeback();
    }
}
